// src/utils/api.js
import axios from "axios";
import { ref } from "vue";
import { useLoadingStore } from "@/store/modules/loading/index";
import { useUserInfoStore } from "@/store/modules/user_info/index";
import { useIsShowLogin } from "@/store/modules/isShowLogin/index.js";

let publicKeyPem = "";
let publicKeyPromise = new Promise((resolve, reject) => {
  window.addEventListener("message", function (event) {
    try {
      if (event.data.method == "get_key") {
        publicKeyPem = event.data.key;
        resolve(publicKeyPem); // 公钥加载完成后调用 resolve
      }
    } catch (error) {
      console.error("Error while processing the message:", error);
      reject(error); // 可以选择在发生错误时拒绝 Promise
    }
  });
});


const _0x1649 = [
  "encrypt",
  "charCodeAt",
  "encode",
  "indexOf",
  "replace",
  "trim",
  "-----END\x20PUBLIC\x20KEY-----",
  "RSA-OAEP",
];
const _0x34d4 = function (_0x164965, _0x34d4aa) {
  _0x164965 = _0x164965 - 0x0;
  let _0x4edf05 = _0x1649[_0x164965];
  return _0x4edf05;
};
async function importPublicKey(_0x3983f9) {
  const _0x4c0cc1 = "-----BEGIN\x20PUBLIC\x20KEY-----";
  const _0x157328 = _0x34d4("0x6");
  let _0x30b2e0 = _0x3983f9["substring"](
    _0x3983f9[_0x34d4("0x3")](_0x4c0cc1) + _0x4c0cc1["length"],
    _0x3983f9["indexOf"](_0x157328)
  )[_0x34d4("0x5")]();
  _0x30b2e0 = _0x30b2e0[_0x34d4("0x4")](/[\r\n]+/g, "");
  const _0x38ab1a = atob(_0x30b2e0);
  const _0x4dc76b = new Uint8Array(_0x38ab1a["length"]);
  for (let _0x311365 = 0x0; _0x311365 < _0x38ab1a["length"]; ++_0x311365) {
    _0x4dc76b[_0x311365] = _0x38ab1a[_0x34d4("0x1")](_0x311365);
  }
  return await crypto["subtle"]["importKey"](
    "spki",
    _0x4dc76b,
    { name: "RSA-OAEP", hash: { name: "SHA-1" } },
    ![],
    [_0x34d4("0x0")]
  );
}
async function encryptMessage(_0x3bf3cb, _0x3f0ac3) {
  const _0x314c16 = new TextEncoder();
  const _0x2214da = _0x314c16[_0x34d4("0x2")](_0x3f0ac3);
  const _0x3d58eb = await crypto["subtle"]["encrypt"](
    { name: _0x34d4("0x7") },
    _0x3bf3cb,
    _0x2214da
  );
  return btoa(String["fromCharCode"](...new Uint8Array(_0x3d58eb)));
}



const lang = ref("");
if (localStorage.getItem("lang") == "en") {
  lang.value = "en";
} else {
  lang.value = "zh";
}

const isShowLoginStore = useIsShowLogin();
const loadingStore = useLoadingStore(); //loadding组件状态
const user_infoStore = useUserInfoStore();

const baseURL = window.baseUrl;
// const baseURL = 'https://www.yyfuns.com'; // 测试环境
const path = "/index.php/api/pc";

const api = axios.create({
  baseURL: baseURL + path, // 替换成公司后端API的基本URL
  timeout: 60000, // 请求超时时间，单位：毫秒（10秒）
  headers: {
    "Content-Type": "application/json",
    // 可以根据需要添加其他默认的请求头部信息
  },
});

// 请求拦截器，可在请求发送前进行处理
api.interceptors.request.use(
  async (config) => {
    console.log(config,'config')
    if(config.url != "/send_email"){
      loadingStore.startLoading();
    }
    // 可以在这里对请求config进行修改，如添加token等
    if (user_infoStore.userToken) {
      // console.log('token',user_infoStore.userToken);
      config.headers.Authorization = `Bearer ${user_infoStore.userToken}`;
    }
    // 添加language参数到请求中
    let language = ""; // 设置你需要的语言
    if (localStorage.getItem("lang") == "en") {
      language = "en";
    } else {
      language = "ch";
    }
    // 处理GET请求
    if (config.method === "get") {
      // 如果config.url中已经包含查询参数，使用&符号追加
      // 加载公钥并加密消息
      if (config.url.includes("?")) {
        config.url += `&language=${language}`;
      } else {
        // 如果config.url中没有查询参数，使用?符号追加
        config.url += `?language=${language}`;
      }
    } else if (config.method === "post") {
      // 对于 POST 请求，将 language 参数添加到请求体中
      if (config.data && typeof config.data === "object") {
        // 如果请求体是对象，直接添加 language 参数
        config.data.language = language;
        if(config.url != '/upload/image'){
          console.log('加密加密加密加密加密加密加密1');
          
          await publicKeyPromise;
          console.log('加密加密加密加密加密加密加密2');
          const publicKey = await importPublicKey(publicKeyPem);
          console.log('加密加密加密加密加密加密加密3');
          console.log(publicKey,config.data);
          const EncData = await encryptMessage(
            publicKey,
            JSON.stringify(config.data)
          );
          config.data = {};
          // 加载公钥并加密消息
          config.data.EncData = EncData;
        }
        
      } else if (config.data) {
        // 如果请求体是字符串或其他类型，将其转换为对象进行修改
        try {
          const dataObj = JSON.parse(config.data);

          dataObj.language = language;
          config.data = JSON.stringify(dataObj);
        } catch (e) {
          // 如果不能解析为 JSON，则原样返回
          console.error("Invalid POST data format");
        }
      }
    }
    // else{
    //   config.headers.Authorization = 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJqd3RfYWRtaW4iLCJpYXQiOjE3MjEwMTY3NDEsImV4cCI6MTcyMzY5NTE0MSwibmJmIjoxNzIxMDE2NzQxLCJzdWIiOiJnZmh4cXoxIiwianRpIjoiMjhkNGVkZTUzZDAyZjY1ZWQyZDNmZTE5N2Y0MTJkZWUifQ.ab977589d4361a0ef60f9e46b2c7d0aa3d4037dbbcf727849ae2f490ea4f64e7';
    // }

    return config;
  },
  (error) => {
    // 对请求错误做些什么
    console.log(error);
    // ElMessage.error(error || '请求失败');
    loadingStore.stopLoading();
    return Promise.reject(error);
  }
);

// 响应拦截器，可在接收到响应后进行全局处理
api.interceptors.response.use(
  (response) => {
    // 可以在这里对响应数据进行处理，如统一处理错误码等
    // console.log(response.config.url);
    const currentURL = window.location.href;

    if (
      response.config.url !== "/getUserInfo" &&
      !currentURL.includes("/playgame") &&
      (!currentURL.includes("/gameCenter") || response.config.url.includes("/userGetGift") )
    ) {
      if (
        response.data.code == 5001 ||
        response.data.code == 5002 ||
        response.data.code == 5003 ||
        response.data.code == 6001 ||
        response.data.message == "Token失效"
      ) {
        // if (lang.value == "en") {
        //   ElMessage.warning("Login failed, please log in again");
        // } else {
        //   ElMessage.warning("登陆失效请重新登陆");
        // }
        user_infoStore.clearUserinfo()
        user_infoStore.clearUserToken()
        user_infoStore.clearUserToken_expire()
        if(window.location.hash !== "#/home" || response.config.url.includes("/userGetGift")){
          isShowLoginStore.showLogin();
        }
        
      }
    }

    loadingStore.stopLoading();
    return response.data;
  },
  (error) => {
    // 对响应错误做些什么
    // console.log(error);
    try {
      if (error.code === "ERR_NETWORK" || error.response.status === 500) {
        if (lang.value == "en") {
          ElMessage.warning("Server error, please try again later");
        } else {
          ElMessage.error("服务器出错，请稍后再试");
        }
      } else {
        ElMessage.error(error.message || "请求失败");
      }
    } catch (error) {
      console.log(error);
    }
    loadingStore.stopLoading();

    return Promise.reject(error);
  }
);

export default api;
